/* eslint-disable @typescript-eslint/no-explicit-any */
import { Cell, CellProps, Option } from '../../doc/cell';
import { PopList } from '@knno/ui/popList';

function findOption(options: Option[], code: unknown): Option | null {
	for (const option of options) {
		if (option.code === code) return option;
		if (option.children) {
			const opt = findOption(option.children, code);
			if (opt) return opt;
		}
	}
	return null;
}

export async function select(cell: Cell, attrs: CellProps) {
	function openSelect(options: Option[]) {
		PopList.show(
			options,
			{
				text: 'name',
				value: 'code',
				children: attrs.childrenField,
				expand: 'expand',
			},
			{
				refer: cell,
				activeValue: attrs.multiSelect ? undefined : cell.getValue()?.code,
				selected: attrs.multiSelect ? cell.getValue() : undefined,
				useSearch: attrs.searchBox ?? false,
				width: attrs.popupWidth,
				multiSelect: attrs.multiSelect,
				disableField: attrs.disableField,
				noSelectField: attrs.noSelectField,
				resultTextField: attrs.resultTextField,
				resultFullPath: attrs.resultFullPath,
				focus: true,
			}
		)
			.onSelect((code, name) => {
				if (code === null || code === undefined) {
					cell.setValue(undefined);
				} else {
					cell.setValue({ code, name });
				}
				cell.text(name + '');
			})
			.onSelectMultiple((selected) => {
				cell.setValue(selected.map((item) => ({ code: item.value, name: item.text })));
				cell.text(selected.map((row) => row.text).join('; '));
			});
	}
	let options = typeof attrs.options === 'function' ? attrs.options() : attrs.options;
	if (options) {
		options = await options;
	} else {
		options = [];
	}
	options = options.map((item) => {
		if (typeof item === 'string') {
			return {
				code: item,
				name: item,
			};
		} else return item;
	});

	if (attrs.multiSelect) {
		cell.text(
			cell
				.getValue()
				.map((row: any) => row.name)
				.join('; ')
		);
	} else {
		const value = cell.getValue();
		const opt = findOption(options as Option[], value?.code);
		if (opt) {
			cell.text(value.name);
		} else {
			cell.setValue(undefined);
			cell.text('');
		}
	}
	cell.addClass('select');
	cell.on('click', () => {
		if (!attrs.readonly) {
			openSelect(options as Option[]);
		}
	});
	cell.on('keydown', (evt) => {
		if (evt.key === ' ') {
			evt.preventDefault();
			evt.stopPropagation();
		}
	});
	cell.on('keypress', (evt) => {
		if (evt.key === ' ' || evt.key === 'Space' || evt.key === 'Enter') {
			evt.preventDefault();
			evt.stopPropagation();
			if (!attrs.readonly) {
				openSelect(options as Option[]);
			}
		}
	});
}
